package vip.xiaonuo.bi.core.datasource.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther: 顾育司
 * @Description excel 导出工具类
 * @date: 2024/1/9
 */
@Slf4j
public class ExcelExportUtils {


//    public static void main(String[] args) {
//        // 创建数据列表
//        List<List<String>> data = new ArrayList<>();
//        data.add(Arrays.asList("A1", "B1", "C1"));
//        data.add(Arrays.asList("A2", "B2", "C2"));
//        data.add(Arrays.asList("A3", "B3", "C3"));
//        List<String> list = Arrays.asList("Column1", "Column2", "Column3");
//        // 导出Excel文件
//        String fileName = "output2.xlsx";
//        exportToExcel(data, fileName,"测试sheet",list);
//    }

    public static void exportToExcel(HttpServletResponse response,List<List<String>> data, String fileName,String sheetName,List<String> head) throws Exception {

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 30);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 水平垂直居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 内容背景白色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont contentWriteFont = new WriteFont();

        // 内容字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        //设置边框样式，细实线
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        // 水平垂直居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                contentWriteCellStyle);



        // 转换数据格式
        List<List<Object>> convertedData = new ArrayList<>();
        for (List<String> rowData : data) {
            List<Object> convertedRow = new ArrayList<>();
            for (String cellData : rowData) {
                convertedRow.add(cellData);
            }
            convertedData.add(convertedRow);
        }

        // 创建WriteSheet对象
        WriteSheet writeSheet = EasyExcel.writerSheet(0).sheetName(sheetName).head(getHead(head)).build();


        // 写excel
//        ExcelWriter excelWriter1 = EasyExcel.write(file.getPath())
        ExcelWriter excelWriter1 = EasyExcel.write(response.getOutputStream())
//        WriteSheet build = build1
                // 自定义样式
                .registerWriteHandler(horizontalCellStyleStrategy)
                // 自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 设置第一行字体
                .registerWriteHandler(new CellWriteHandler() {
                    @Override
                    public void afterCellDispose(CellWriteHandlerContext context) {
                        WriteCellData<?> cellData = context.getFirstCellData();
                        WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                        Integer rowIndex = context.getRowIndex();
                        if (rowIndex == 0) {
                            WriteFont headWriteFont = new WriteFont();
                            headWriteFont.setFontName("宋体");
                            headWriteFont.setBold(true);
                            headWriteFont.setFontHeightInPoints((short) 16);
                            writeCellStyle.setWriteFont(headWriteFont);
                        }
                    }
                })
                // 设置表头行高
                .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                    @Override
                    protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                        if (relativeRowIndex == 0) {
                            // 表头第一行
                            row.setHeightInPoints(34);
                        } else {
                            // 表头其他行
                            row.setHeightInPoints(30);
                        }
                    }

                    @Override
                    protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                        // 内容行
                        row.setHeightInPoints(20);
                    }
                }).build();

        excelWriter1.write(convertedData, writeSheet);

        // 关闭ExcelWriter对象
        excelWriter1.finish();
    }

//    private static List<List<String>> getHead() {
//        List<List<String>> head = new ArrayList<>();
//        head.add(Arrays.asList("Column1","Column4"));
//        head.add(Arrays.asList( "Column2","Column4"));
//        head.add(Arrays.asList("Column3","Column4"));
//        return head;
//    }
        private static List<List<String>> getHead(List<String> headList) {
        return   headList.stream().map(item->Arrays.asList(item)).collect(Collectors.toList());
    }


    public static void setExcelHeader(HttpServletResponse response, String fileName) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLUtil.encode(fileName+".xlsx"));
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    /**
     * 下载文件
     *
     * @author xuyuxiang
     * @date 2022/7/31 10:57
     */
    public static void download(String fileName, byte[] fileBytes, HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode(fileName));
            response.addHeader("Content-Length", "" + fileBytes.length);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream;charset=UTF-8");
            IoUtil.write(response.getOutputStream(), true, fileBytes);
        } catch (IOException e) {
            log.error(">>> 文件下载异常：", e);
        }
    }


}
